<?php

namespace app\admin\controller;

use app\models\{Admin, AdminLogin};
use app\validate\Admin as Validate;
use think\Db;

class Index extends Base
{
    public function login()
    {
        $admin_id = session('admin_id');
        if (Admin::get($admin_id)) {
            return redirect('/main/index');
        }
        $data = $this->request->post();
        if ($this->request->isPost()) {
            $validate = new Validate();
            if (!$validate->scene('login')->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            $admin = Admin::get(['username' => $data['username']]);

            try {
                if ($admin == false) {
                    throw new \Exception("账号或密码错误", 1);
                }
                if ($admin['password'] != md5(md5($data['password']) . md5($admin['entry']))) {
                    throw new \Exception("账号或密码错误", 1);
                }
            } catch (\Exception $e) {
                (new AdminLogin())->insert([
                    'uid'      => '00',
                    'username' => $data['username'],
                    'login_ip' => request()->ip(),
                    'info'     => $e->getMessage(),
                    'created' => date('Y-m-d H:i:s')
                ]);
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            (new AdminLogin())->insert([
                'uid'      => $admin['id'],
                'username' => $admin['username'],
                'login_ip' => request()->ip(),
                'info'     => '登陆成功',
                'created' => date('Y-m-d H:i:s')
            ]);

            session('admin_id', $admin['id']);
            $admin->save([
                'login_num' => $admin['login_num'] + 1,
                'login_ip' => request()->ip(),
            ], [
                'id' => $admin['id']
            ]);
            return json(['code' => 0, 'msg' => '登陆成功', 'url' => url('main/index')]);
        }

        return view(null, [
            'data' => $data
        ]);
    }

    public function logout()
    {
        session('admin_id', null);
        $this->redirect('index/login');
    }
}
